package com.hmall.gateway.filter;

import com.hmall.common.exception.UnauthorizedException;
import com.hmall.common.utils.CollUtils;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


/**
 * Jwt登录校验全局过滤器
 *
 * @author xiaopeng
 * @version 1.0
 */
@Component
@RequiredArgsConstructor
@EnableConfigurationProperties(AuthProperties.class)
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    private final JwtTool jwtTool;

    //Spring Framework 提供的一个路径匹配工具类，用于处理路径模式的匹配操作。
    //它支持通配符匹配、路径变量解析等功能，常用于 Web 应用程序中处理 URL 路径的匹配规则。
    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取Request
        ServerHttpRequest request = exchange.getRequest();
        // 2.判断是否不需要拦截
        if (isExclude(request.getPath().toString())) {
            // 无需拦截，直接放行
            return chain.filter(exchange);
        }
        // 3.获取请求头中的token
        String token = null;
        List<String> authorization = request.getHeaders().get("authorization");
        if (!CollUtils.isEmpty(authorization)) {
            token = authorization.get(0);
        }
        // 4.校验并解析token
        Long userId;
        try {
            userId = jwtTool.parseToken(token);
        } catch (UnauthorizedException e) {
            //如果无效，拦截
            ServerHttpResponse response = exchange.getResponse();
            //设置401登录错误码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // 5.如果有效，将在网关获取到的用户信息，通过请求头的方式传递给其他微服务
        String userInfo = userId.toString();
        // 通过mutation创建一个新的ServerWebExchange实例，以添加请求头信息
        ServerWebExchange ex = exchange.mutate() //mutate就是对转发到下游的请求做更改
                // 在请求头中添加"user-info"，值为userInfo变量
                .request(builder -> builder.header("user-info", userInfo))
                // 构建并获取修改后的ServerWebExchange实例
                .build();

        // 6.放行
        return chain.filter(ex);
    }

    /**
     * 使用路径匹配工具AntPathMatcher,判断是否包括白名单路径
     *
     * @param antPath
     * @return
     */
    private boolean isExclude(String antPath) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(pathPattern, antPath)) {
                return true;
            }
        }
        return false;
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
